<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索关键字"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="系统拥有者" prop="ownerId">
        <el-select
          v-model="form.ownerId"
          placeholder="请选择"
          class="!w-[180px]"
        >
          <el-option
            v-for="item in ownerList"
            :key="item.agentId"
            :label="item.username"
            :value="item.agentId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户" prop="userId">
        <el-select
          ref="userSelectRef"
          v-model="form.userId"
          placeholder="请选择"
          filterable
          remote
          :remote-method="onKeywordInput"
          class="!w-[180px]"
          clearable
          @visible-change="onUserDropdownVisibleChange"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
          <template v-if="userLoading" #footer>
            <div class="text-center text-xs text-gray-500">
              <span>加载中...</span>
            </div>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceType">
        <el-select
          v-model="form.serviceType"
          placeholder="请选择"
          filterable
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in taskConfigStore.serviceTypes"
            :key="item.standardCode"
            :label="item.displayName"
            :value="item.standardCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-select
          v-model="form.country"
          placeholder="请选择"
          filterable
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in taskConfigStore.allCountryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in taskConfigStore.getStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="time">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          class="!w-[220px]"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
        <el-button
          type="success"
          :icon="useRenderIcon(Document)"
          :loading="exporLoading"
          @click="exportData"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="id" label="任务ID" width="80" />
      <el-table-column prop="taskNo" label="任务编号" width="200" />
      <el-table-column prop="title" label="任务名称" width="160" />
      <el-table-column prop="username" label="用户名称" width="200" />
      <el-table-column
        :formatter="formatOwner"
        label="系统拥有者"
        width="150"
      />
      <el-table-column prop="fileId" label="上传文件ID" width="300" />
      <el-table-column
        prop="thirdPartyTaskId"
        label="第三方任务ID"
        width="260"
      />
      <el-table-column prop="serviceType" label="服务类型" width="120" />
      <el-table-column
        prop="apiProvider"
        :formatter="formatterApiProvider"
        label="API提供商"
        width="160"
        align="center"
      />
      <el-table-column prop="country" label="国家" width="100" />
      <el-table-column prop="totalCount" label="数据总量" width="120" />
      <el-table-column prop="effectiveCount" label="有效数量" width="120" />
      <el-table-column prop="successCount" label="成功数量" width="120" />
      <el-table-column
        prop="processingDurationText"
        label="处理时长"
        width="100"
      />
      <el-table-column prop="progress" label="进度" width="100" />
      <el-table-column prop="taskStatus" label="状态" width="100" />
      <el-table-column
        prop="lastSyncTime"
        :formatter="val => handleAutoUTC8(val.lastSyncTime)"
        label="最后同步时间"
        min-width="200"
      />
      <el-table-column
        prop="updateTime"
        :formatter="val => handleAutoUTC8(val.updateTime)"
        label="更新时间"
        min-width="200"
      />
      <el-table-column
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
        min-width="200"
      />
      <el-table-column label="操作" fixed="right" width="340">
        <template #default="scope">
          <div
            class="flex items-center justify-center text-center gap-1 text-sm"
          >
            <el-popover
              v-if="activeDown(scope.row.serviceType)"
              placement="bottom"
              :disabled="scope.row.outputLoading"
              trigger="click"
              popper-style="padding: 0;min-width:auto;width:auto"
            >
              <template #reference>
                <el-button
                  link
                  type="primary"
                  size="small"
                  :loading="scope.row.outputLoading"
                >
                  下载结果文件
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
              </template>
              <div class="down-group">
                <el-button
                  v-for="it in downList"
                  :key="it.value"
                  text
                  type="primary"
                  size="small"
                  @click="handleCommand(scope.row.id, it.value)"
                >
                  {{ it.label }}
                </el-button>
              </div>
            </el-popover>
            <el-button
              v-else
              link
              type="primary"
              size="small"
              :loading="scope.row.outputLoading"
              @click="handleDownload(scope.row.id)"
            >
              下载结果文件
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              :loading="scope.row.inputLoading"
              @click="handleDownload(scope.row.id, 'INPUT')"
            >
              下载上传文件
            </el-button>
            <!-- <el-button
              link
              type="success"
              size="small"
              @click="syncTask(scope.row.id)"
            >
              重新同步
            </el-button> -->
            <el-button
              link
              type="danger"
              size="small"
              :disabled="scope.row.taskStatus === '已退款'"
              @click="handleRefund(scope.row.id)"
            >
              退款
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <DownloadFileDialog
      ref="downloadFileDialogRef"
      :downloadApi="downloadAdminFilterResultFile"
    />
  </div>
</template>

<script lang="ts" setup>
import { handleAutoUTC8 } from "@/utils/tools";
import { reactive, ref, onMounted, watch, h, nextTick } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ArrowDown } from "@element-plus/icons-vue";
import Refresh from "@iconify-icons/ep/refresh";
import Document from "@iconify-icons/ep/document";
import {
  getAllTasks,
  downloadAdminTaskResultFile,
  downloadAdminFilterResultFile,
  downloadAdminAllResultFile,
  exportTasks,
  syncAdminTaskStatus,
  adminRefund
} from "@/api/adminTaskApi";
import { useTaskConfigHook } from "@/store/modules/taskConfig";
import { message } from "@/utils/message";
import { type ElSelect, ElMessageBox } from "element-plus";
import DownloadFileDialog from "@/components/DownloadFileDialog.vue";
import { getAdminAgentsList } from "@/api/adminAgentApi";
import { useRemotePagedSelect } from "@/composables/useRemotePagedSelect";
import {
  userSelectFetcher,
  type UserItem
} from "@/composables/userSelectFetcher";

// 用户下拉：远程搜索 + 触底加载
const {
  list,
  loading: userLoading,
  onKeywordInput,
  onDropdownScroll
} = useRemotePagedSelect<UserItem>({
  pageSize: 20,
  autoLoad: true,
  debounceMs: 300,
  fetcher: userSelectFetcher
});

const userSelectRef = ref<InstanceType<typeof ElSelect> | null>(null);
let userDropdownWrapEl: HTMLElement | null = null;

function onUserDropdownVisibleChange(visible: boolean) {
  if (visible) {
    nextTick(() => {
      const popperEl = userSelectRef.value?.popperRef as
        | HTMLElement
        | undefined;
      // 在该选择器自己的 popper 里找 wrap
      userDropdownWrapEl =
        popperEl?.querySelector(".el-select-dropdown__wrap") ?? null;
      userDropdownWrapEl?.addEventListener("scroll", onDropdownScroll, {
        passive: true
      });
    });
  } else {
    userDropdownWrapEl?.removeEventListener("scroll", onDropdownScroll);
    userDropdownWrapEl = null;
  }
}
const taskConfigStore = useTaskConfigHook();
const formRef = ref();
const loading = ref(false);
const downloadFileDialogRef = ref();
const form = reactive({
  ownerId: 0,
  userId: "",
  serviceType: "",
  time: "",
  keyword: "",
  status: "",
  country: "",
  startDate: "",
  endDate: ""
});
const downList = [
  {
    label: "下载一天活跃",
    value: 1
  },
  {
    label: "下载三天活跃",
    value: 3
  },
  {
    label: "下载七天活跃",
    value: 7
  },
  {
    label: "下载全部",
    value: "all"
  },
  {
    label: "自定义活跃",
    value: "custom"
  }
];
const formatterApiProvider = (row: any) => {
  const nameObj = {
    TNTPUB: "T",
    APIFOX: "A"
  };
  return nameObj[row.apiProvider] || row.apiProvider;
};
const handleRefund = (id: number) => {
  ElMessageBox.confirm("确认要退款吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const { detailMessage, message: text } = await adminRefund(id);
      message(
        h(
          "p",
          {
            class:
              "flex flex-col items-center justify-center text-center gap-1 text-sm"
          },
          [
            text ? h("span", null, text) : null,
            detailMessage ? h("span", null, detailMessage) : null,
            !text && !detailMessage ? h("span", null, "退款成功") : null
          ]
        ),
        {
          dangerouslyUseHTMLString: true,
          type: "success",
          center: true
        }
      );
      onSearch();
    })
    .catch(() => {});
};
const exporLoading = ref(false);
const exportData = async () => {
  exporLoading.value = true;
  const { userId, serviceType, status, country } = form;
  const params = {
    userId,
    serviceType,
    country,
    status
  };
  try {
    await exportTasks(params);
  } catch (err) {
    console.error("下载失败：", err);
  } finally {
    exporLoading.value = false;
  }
};
const pagination = reactive({
  total: 0,
  pageSize: 20,
  currentPage: 1
});

const activeDown = (name: string) => {
  const tags = ["live", "profile"];
  return tags.some(tag => name.includes(tag));
};
const handleCommand = async (id: number, command: string | number) => {
  const index = tableData.value.findIndex(item => item.id === id);
  if (command === "custom") {
    downloadFileDialogRef.value?.open(id);
  } else if (command === "all") {
    try {
      tableData.value[index].outputLoading = true;
      await downloadAdminAllResultFile(id, { fileType: "OUTPUT" });
    } catch (error) {
      console.log(error);
    } finally {
      tableData.value[index].outputLoading = false;
    }
  } else {
    try {
      tableData.value[index].outputLoading = true;
      await downloadAdminFilterResultFile(id, { activeDaysThreshold: command });
    } catch (error) {
      console.log(error);
    } finally {
      tableData.value[index].outputLoading = false;
    }
  }
};
const handleDownload = async (id: number, fileType = "OUTPUT") => {
  const index = tableData.value.findIndex(item => item.id === id);
  try {
    if (fileType === "OUTPUT") {
      tableData.value[index].outputLoading = true;
    } else {
      tableData.value[index].inputLoading = true;
    }
    await downloadAdminTaskResultFile(id, { fileType });
  } catch (err) {
    console.log(err);
  } finally {
    if (fileType === "OUTPUT") {
      tableData.value[index].outputLoading = false;
    } else {
      tableData.value[index].inputLoading = false;
    }
  }
};
const syncTask = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      "该操作会清空本地缓存，重新拉取文件，谨慎操作",
      "同步提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    const { detailMessage, message: text } = await syncAdminTaskStatus(id);
    message(
      h(
        "p",
        {
          class:
            "flex flex-col items-center justify-center text-center gap-1 text-sm"
        },
        [
          text ? h("span", null, text) : null,
          detailMessage ? h("span", null, detailMessage) : null,
          !text && !detailMessage ? h("span", null, "同步成功") : null
        ]
      ),
      {
        dangerouslyUseHTMLString: true,
        type: "success",
        center: true
      }
    );
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
const tableData = ref([]);

watch(
  () => form.time,
  (newVal, oldVal) => {
    if (newVal) {
      form.startDate = newVal[0];
      form.endDate = newVal[1];
    } else {
      form.startDate = "";
      form.endDate = "";
    }
  }
);

const onSearch = async () => {
  try {
    const { time, ...reset } = form;
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...reset
    };
    const { data } = await getAllTasks(params);
    const { records, total, size, current } = data;
    tableData.value = records.map(item => {
      return {
        ...item,
        inputLoading: false,
        outputLoading: false
      };
    });
    pagination.total = total;
    pagination.pageSize = size;
    pagination.currentPage = current;
  } catch (error) {
    console.log(error);
  }
};
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  form.startDate = "";
  form.endDate = "";
  pagination.currentPage = 1;
  onSearch();
};
const ownerList = ref([
  {
    agentId: 0,
    username: "主系统"
  }
]);
const formatOwner = (row: any) => {
  return (
    ownerList.value.find(item => item.agentId === row.ownerId)?.username ||
    "主系统"
  );
};
const queryOwnerList = async () => {
  const res = await getAdminAgentsList({ page: 1, size: 100 });
  const agentList = res?.data?.records || [];
  ownerList.value = [...ownerList.value, ...agentList];
};
onMounted(() => {
  onSearch();
  queryOwnerList();
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
.down-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  .el-button {
    margin: 0;
  }
}
</style>
